/**
 * 地块绘制工具
 */
import Base from "./Base";
import turf from "turf"
import mapboxgl from "mapbox-gl";

export default class DrawArea extends Base {
  constructor(map,{callBack:callBack=null,errorCallBack:errorCallBack=null}={}) {
    super(map,'DrawArea',{callBack:callBack,errorCallBack:errorCallBack});
  }

  start() {
    super.start();
    this.draw = new MapboxDraw({
      displayControlsDefault: false,
      controls: {}}
    );
    this.map.addControl(this.draw);
    this.draw.changeMode(this.draw.modes.DRAW_POLYGON);
    this.updateEvent=(e)=>{
      this.update(e)
    };
    this.map.on('draw.update_polygon', this.updateEvent);
    this.createEvent=(e)=>{
      //检测自相交
      let featureSet= turf.kinks(e.features[0]);
      if(featureSet.features.length>0){
        this.error("多边形自相交");
      }else {
        this.finish(e.features[0])
      }
    };
    this.map.on('draw.create', this.createEvent);
  }

  update(e){
    this.clearPopup();
    let area=turf.area(e.feature);
    let center=turf.center(e.feature);
    //
    // this.popup = new mapboxgl.Popup({
    //   closeButton: false,
    //   closeOnClick:false,
    //   className:this.popupClassName
    // });
    // this.popup.setLngLat(center.geometry.coordinates)
    //   .setText((area*0.0015).toFixed(2)+"亩")
    //   .addTo(this.map);
  }

  /**
   * 移除长度文字
   */
  clearPopup(){
    if(this.popup){
      this.popup.remove();
      this.popup=null;
      super.clearPopup();
    }
  }
  close() {
    this.clear();
    this.clearEvent();
  }

  clear() {
    this.clearPopup();
    this.clearMap();
  }

  clearMap() {
    if(this.draw){
      this.draw.deleteAll();
    }
  }

  clearEvent() {
    super.clearEvent();
    this.map.off('draw.update_polygon',this.updateEvent);
    this.map.off('draw.create',this.createEvent);
    if(this.draw){
      this.map.removeControl(this.draw);
      this.draw=null;
    }
  }
}
